/****************************************************
          File Name:mq_receive.c
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Sat 20 Sep 2014 10:11:46 AM CST
*****************************************************/

#include"posix_ipc.h"

int main(int argc,char *argv[])
{
    if(argc<2 || strcmp(argv[1],"--help")==0)
    {
        printf("%s /mq\n",argv[0]);
        exit(EXIT_FAILURE);
    }

    mqd_t mq;
    struct mq_attr attr;
    char *buf;
    size_t bytes;

    if((mq=mq_open(argv[1],O_RDONLY))==(mqd_t)-1)
        err("open");
    if(mq_getattr(mq,&attr)==-1)
        err("get_attr");

    buf=malloc(attr.mq_msgsize);
    if(buf==NULL)
        err("malloc");

    for(;;)
    {
        if(mq_receive(mq,buf,attr.mq_msgsize,0)==-1)
            if(errno==EAGAIN)
                break;
        else
            err("receive");
        bytes=write(STDOUT_FILENO,buf,attr.mq_msgsize);
        if(bytes==-1)
            err("write");
    }

    exit(EXIT_SUCCESS);
}
